package com.cyber.utils;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;


import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class AlipayTemplate {

    //在支付宝创建的应用的id
    private   String app_id = "2016082000291568";

    // 商户私钥，您的PKCS8格式RSA2私钥
    private  String merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCD/6vZ5jpo17B5BOOm3LlNkrtE+8tsZYVpdmFE+j7RE4Dme+lk14do6J6lmOxQFLAlrcev9WP3XQ21os4lcolN3NVYYyhv1NqxYnromBjuNs3Wci5SSCrv3VTwnDzRv+CO9jLFePicT/Dz2YJr5IbvpZ/PODidecH+0SxZRgOGN42q8DAVFwVqyMNpWAD3FIdQOJzCWYLSvdiVdhKWhduHIQQw8R1W+89q2fHL6cMTDweaJjcjq7/2xdPTkxkBVY9htIinFe6quFbSI0RDTZNeRndQoOK4RrLyK20TNsivSFACLQnjAnmCZJOYWAlKT2iFJSijlUaOkDOdx4aIEcNZAgMBAAECggEAWuDvL4FsG3zMmjV8iwiSZ88rMc5t+r5WwQpo47WrBAV6jLUpNm2RY/AsMfT8VhI4SGjB/+piHg+p/bEOXwfhcoMlO8phL8WLn+8ekf8NwwxmYUuRisL3FNf8v//Be+OwNp1YzU6BVBVR3oGVYrUfFeWhBmk9yWXn44meEAS9Lm0WfV5Kt4CG1VyOhLzZJIz8ffR5VRZ27dGF4vMAuqlrhfm1mjj8J57BRxvFO0wk0iVQ3TBs5YFDOga8jbFKd+vDiyB5RX2tbvi5Rig8GMxNRrB0M59z/YsG+x7A0Dm4uq5REvTBrgYbpUYM1964xehD0IvgddyVCzzM5f5oLBA/5QKBgQDY2HeneLmQ2hAzXxuX+i1KZzTy27BZ3LEZ3NRgheBaZjHGJ2S/F3M90vLvDQuyaxK/Oc3hlcEw5uJMhBmwJ/ju3gyur/oIgnoO/cDNZBmhoj8N8mxKeX4ZcNRF02krrQ4tY69yEVyN890yGIM8/38ALddjogOr5x1pyqgic6vqkwKBgQCb1TfWMutRI8j0V6xeW+KEaOAgye+zP6gtBQcYuFAXrR9+STEZlo5hDPAUuCF2I4oW5j8wK9LrF6lwSM8BusYhmfVoYRwZGk1h5R0AKBb9xiQR2g0tLw5h4U5HtsDnlhlGYlb2nYDCfSQQMOKWQ6u3wBG1XBdiHJfAVuzQst8R4wKBgQCSIl+QxzUXPz3HwQKRixHWoHL4b8EK7kWTzlR5r/8gLNrCVW35sc4CDhWVsE7/sFTz9fqfWhLV5+L9+dBt/KIwKAiX+RQhg/zJ+YxjXmA/o12nAoakMfgfIQCNBgpMWtXBFPr5fmXHbF7XEdnv06c88afEBz0+LgSOdPqWLSngbQKBgGyo9nBTvSYs77kBUV3ScFan0nDKnmu83YXW1aX1D1QTEby7SJNxGgKuRNINurdn/KgPEMyEImRvcWSsQDwSgol3k1mfLTqLzp2OZvRu/+kgupIAG+P/xeWWd0EmO8jALwuXEtCP7vKu0/C+RaFFun08Xpy5hEyTZ3Vkp2i28TjFAoGAK5UqG9w4LIuvMac9N43WEWrxaWU/gT7ywn06XaFcqBeycrSIxoHQvYrWCvmli4FE0DyS9uD12FLsbogAoWxXJppmNOD8tNdSiFRNeGYZxvJ1ZAeQeXSOrhpti7WsolS/QHJJzPIT7w9BY7fk3Ppnr1DrLqB+yTSVtJRb4uMu5us=";
    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    private  String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0GTHzyOZ+sVmMikOMaqMFxK5AG/AFpyPwsYgKd+RvZtqUpwgL89WVXGdcQsbdLn9zAGZbIGH0PbK2G68NnKV2URjQ2UDpDRCyTv5FFiCELts/xAVIN+9yGlaira9j38NM/7jifcILNwFTj4u1lS3gw8CK1gsXHhzkfhiMu6afxU0qbnwVD3V+4CGScw7tq88kwhXXDQ/aOtEjcP29VPb9uTH332LRU1NgkHCgIlJ06+1x1TEnSVOPivOL205OQJbWvMVIKa3EEyPMBypHraLOcVxgrlduRQyMJP+YWQpS9WMfWoTjKn34KSdt9ZtNeo9feHZS7fmMMn2LH0E6z9DdQIDAQAB";
    // 服务器[异步通知]页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    private  String notify_url="http://linux100:8989/order/changeOrderState";

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    //同步通知，支付成功，一般跳转到成功页
    private  String return_url="http://linux100:8989/order/changeOrderState";

    // 签名方式
    private  String sign_type = "RSA2";

    // 字符编码格式
    private  String charset = "utf-8";

    // 支付宝网关； https://openapi.alipaydev.com/gateway.do
    private  String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
    //支付方法
    public  String pay(PayVo vo) throws AlipayApiException {

        //AlipayClient alipayClient = new DefaultAlipayClient(AlipayTemplate.gatewayUrl, AlipayTemplate.app_id, AlipayTemplate.merchant_private_key, "json", AlipayTemplate.charset, AlipayTemplate.alipay_public_key, AlipayTemplate.sign_type);
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金额，必填
        String total_amount = vo.getTotal_amount();
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;

    }
    public boolean rsaCheckV1(HttpServletRequest request){
        Map<String, String> params = convertRequestParamsToMap(request); // 将异步通知中收到的待验证所有参数都存放到map中
        String paramsJson = JSON.toJSONString(params);
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key,
                    charset, sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return signVerified;
    }
    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

    public String getApp_id() {
        return app_id;
    }

    public void setApp_id(String app_id) {
        this.app_id = app_id;
    }

    public String getMerchant_private_key() {
        return merchant_private_key;
    }

    public void setMerchant_private_key(String merchant_private_key) {
        this.merchant_private_key = merchant_private_key;
    }

    public String getAlipay_public_key() {
        return alipay_public_key;
    }

    public void setAlipay_public_key(String alipay_public_key) {
        this.alipay_public_key = alipay_public_key;
    }

    public String getNotify_url() {
        return notify_url;
    }

    public void setNotify_url(String notify_url) {
        this.notify_url = notify_url;
    }

    public String getReturn_url() {
        return return_url;
    }

    public void setReturn_url(String return_url) {
        this.return_url = return_url;
    }

    public String getSign_type() {
        return sign_type;
    }

    public void setSign_type(String sign_type) {
        this.sign_type = sign_type;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public String getGatewayUrl() {
        return gatewayUrl;
    }

    public void setGatewayUrl(String gatewayUrl) {
        this.gatewayUrl = gatewayUrl;
    }
}
